package com.kldy8.kldyw.find.project;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.kldy8.kldyw.FlowLayoutRadioGroup;
import com.kldy8.kldyw.R;
import com.kldy8.kldyw.filmfactory.FilmTalent.FilmTalentAdapter;
import com.kldy8.kldyw.filmfactory.bean.FilmTalent;
import com.kldy8.kldyw.filmfactory.shootingvenue.ShootingVenueActivity;
import com.kldy8.kldyw.find.project.bean.FilmProject;
import com.kldy8.kldyw.find.project.bean.FilmProjectFilter;
import com.kldy8.kldyw.logre.LoginActivity;
import com.kldy8.kldyw.system.ServerApi;
import com.kldy8.kldyw.system.ServerCallBack;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Request;
/**
 * 影视项目
 */
public class ProjectActivity extends AppCompatActivity
{
    private List<FlowLayoutRadioGroup> flowLayoutRadioGroupList;
     /** DrawerLayout */
//    private DrawerLayout mDrawerLayout;
    /** 右边栏 */
//    private RelativeLayout right_drawer;
    /** 右边栏打开/关闭状态 */
    private final static int MSG_MODIFY_RIGHT_ONE = 1;

    private Toolbar toolbar;

    int mPage = 1;

    String mOrder = "";
    String mSort = "d";
    String mCp_hoot_date ="";
    String mCp_release_time,mSearch ="";

    FilmProjectAdapter filmProjectAdapter;
    private XRefreshView refreshView1;


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_project);
        //=========================侧边栏===================================
//        initRightView();

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(getResources().getString(R.string.film_project));//设置主标题
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true); // 决定左上角图标的右侧是否有向左的小箭头, true
        // 有小箭头，并且图标可以点击
        actionBar.setDisplayShowHomeEnabled(false);
        initView();
        initData();
    }

    private Button resetButton;
    private Button makesureButton;

    //初始化侧边栏
//    private void initRightView()
//    {
//        //==========================侧边栏===============
//        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
//        right_drawer = (RelativeLayout) findViewById(R.id.right_drawer);
//
//        resetButton = (Button) right_drawer.findViewById(R.id.resetBtn);
//
//        resetButton.setOnClickListener(new View.OnClickListener()
//        {
//            @Override
//            public void onClick(View view)
//            {
//
//                mCp_hoot_date = "";
//                mCp_release_time = "";
//
//                for (FlowLayoutRadioGroup flowLayoutRadioGroup: flowLayoutRadioGroupList)
//                {
//                    if (flowLayoutRadioGroup.getChildCount() >0)
//                    {
//                        RadioButton button = (RadioButton) flowLayoutRadioGroup.getChildAt(0);
//                        button.setChecked(true);
//                    }
//                }
//            }
//        });
//
//        makesureButton = (Button) right_drawer.findViewById(R.id.makesureBtn);
//        makesureButton.setOnClickListener(new View.OnClickListener()
//        {
//            @Override
//            public void onClick(View view)
//            {
//                initChipsList(1,mOrder,mSort,mCp_hoot_date,mCp_release_time,mSearch);
//                mDrawerLayout.closeDrawers();
//            }
//        });
//
//    }

//    private void initRightViewData(String title ,List<FilmProjectType> scripTypes)
//    {
//        LinearLayout relativeLayout = (LinearLayout) right_drawer.findViewById(R.id.right_main);
//        LayoutInflater inflater = getLayoutInflater();
//        View view = inflater.inflate(R.layout.script_view_group, null);
//        TextView textView = (TextView) view.findViewById(R.id.title_date);
//        FlowLayoutRadioGroup frg= (FlowLayoutRadioGroup) view.findViewById(R.id.flowLayout);
//        flowLayoutRadioGroupList.add(frg);
//        if (scripTypes != null)
//        {
//            textView.setText(title);
//
//            if (scripTypes != null)
//            {
//                for (int i = 0;i<scripTypes.size();i ++)
//                {
//                    final FilmProjectType filmProjectType=scripTypes.get(i);
//                    RadioButton button = new RadioButton(this);
//                    button.setOnClickListener(new View.OnClickListener()
//                    {
//                        @Override
//                        public void onClick(View view)
//                        {
//                            if (filmProjectType != null)
//                            {
//                                if (filmProjectType.fater == 1)
//                                {
//                                    mCp_hoot_date = filmProjectType.key;
//                                }
//                                else
//                                {
//                                    mCp_release_time = filmProjectType.key;
//                                }
//                            }
//                        }
//                    });
//                    button.setText(filmProjectType.name);
//                    button.setTextColor(getResources().getColor(android.R.color.tertiary_text_dark));
//                    frg.addView(button);
//                }
//            }
//        }
//        relativeLayout.addView(view);
//    }

    private void initData()
    {
        initChipsList(true,1,"","a","","","");
    }




    /**
     * 影视项目列表
     * @param page 页码（默认1）
     * @param order 排序：cp_repay投资回报率/cp_current_cnt支持人数
     * @param sort  排序方式：a升序/d降序
     * @param cp_hoot_date 拍摄日期
     * @param cp_release_time 上映时间
     * @param search 搜索
     * page int 页码（默认1）
     */
    private void initChipsList(final boolean isInit, int page , String order , String sort, String cp_hoot_date, String cp_release_time, String search)
    {
        Log.e("page",""+page);
        Log.e("order",""+order);
        Log.e("sort",""+sort);
        Log.e("cp_hoot_date",""+cp_hoot_date);
        Log.e("cp_release_time",""+cp_release_time);
        Log.e("search",""+search);

        ServerApi.chips_list("" + page,""+ order, ""+sort,""+cp_hoot_date, "" + ""+cp_release_time
                ,""+search,new ServerCallBack()
                {
                    @Override
                    public void onError(Request request, Exception e)
                    {
                        if (refreshView1!=null)
                        {
                            refreshView1.stopRefresh();
                            refreshView1.stopLoadMore();
                        }
                        Toast.makeText(ProjectActivity.this,getResources().getString(R.string.error_system),Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onResponse(String response) throws JSONException
                    {
                        Log.e("......",response.toString());
                        Log.e("page1",""+mPage);

                        ArrayList filmProjectList =  filmProjectList = new ArrayList<FilmProject>();


                        JSONObject jsonObject = new JSONObject(response);
                        if ("0".equals(jsonObject.optString("code")))
                        {
                            mPage++;

                            if (isInit == true)
                            {
                                mPage = 2;
                            }
                            JSONObject objectData = jsonObject.optJSONObject("data");
                            JSONObject objectfilter = objectData.optJSONObject("filter");
                            FilmProjectFilter filmProjectFilterJSR = FilmProjectFilter.resolution(objectfilter);
                            if (filmProjectFilterJSR != null)
                            {
                                filmProjectFilter = filmProjectFilterJSR;
                            }

                            JSONArray objectList = objectData.optJSONArray("list");
                            if (null != objectList && objectList.length()>0)
                            {
                                for (int i = 0; i < objectList.length(); i++)
                                {
                                    JSONObject object = objectList.optJSONObject(i);
                                    FilmProject filmProject = FilmProject.resolution(object);
                                    if (filmProject != null)
                                    {
                                        filmProjectList.add(filmProject);
                                    }
                                }
                            }

                            //这里是更新侧边栏
//                            Message message = new Message();
//                            message.what = MSG_MODIFY_RIGHT_ONE;
//                            handler.sendMessage(message);

                            filmProjectAdapter.replaceOrAdd(isInit,filmProjectList);
                            filmProjectAdapter.notifyDataSetChanged();

                        }
                        else  if ("11005".equals(jsonObject.optString("code")))
                        {
                            Toast.makeText(ProjectActivity.this, "暂无数据", Toast.LENGTH_LONG).show();
                        }
                        else  if ("10004".equals(jsonObject.optString("code")))
                        {
                            Intent intent2 = new Intent();
                            intent2.setClass(ProjectActivity.this, LoginActivity.class);
                            startActivity(intent2);
                            ProjectActivity.this.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
                        }

                        if (refreshView1!=null)
                        {
                            refreshView1.stopRefresh();
                            refreshView1.stopLoadMore();
                        }
                    }
                });
    }


    ListView listview;

    TextView tv1_1;
    TextView tv1_2;
    TextView tv1_3;

    private void initView()
    {

        ListView list_view = (ListView) findViewById(R.id.list_view);
        filmProjectAdapter = new FilmProjectAdapter(this, new ArrayList<FilmProject>());
        list_view.setAdapter(filmProjectAdapter);


        refreshView1 = (XRefreshView) findViewById(R.id.xrefreshview);
        refreshView1.setPullLoadEnable(true);

        //设置刷新完成以后，headerview固定的时间
        refreshView1.setPinnedTime(1000);
        refreshView1.setPullLoadEnable(true);
        refreshView1.setMoveForHorizontal(true);
        refreshView1.setAutoLoadMore(true);
        refreshView1.setEmptyView(R.layout.layout_emptyview);
        refreshView1.getEmptyView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshView1.startRefresh();
            }
        });

        refreshView1.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {

            @Override
            public void onRefresh() {
                requestData();
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                morePeopleData();
            }
        });


        tv1_1 = (TextView) findViewById(R.id.tv_1);
        tv1_1.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
//                String all = getResources().getString(R.string.all);
//                if (allClickTime%2==0)
//                {
//                    all = all + "∧";
//                    tv1_1.setText(all);
//                    mOrder = "";
//                    mSort = "a";
//                }
//                else
//                {
//                    all = all + "∨";
//                    tv1_1.setText(all);
//                    mOrder = "";
//                    mSort = "d";
//                }

                allClickTime++;
//              initChipsList(1,mOrder,mSort,mCp_hoot_date,mCp_release_time,mSearch);


                String return_investment = getResources().getString(R.string.return_investment);
                tv1_2.setText(return_investment);
                String support_number = getResources().getString(R.string.support_number);
                tv1_3.setText(support_number);
            }
        });
        tv1_2 = (TextView) findViewById(R.id.tv_2);
        tv1_2.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                    String all = getResources().getString(R.string.return_investment);
                    if (returnInvestmentClickTime%2==0)
                    {
                        all = all + "∧";
                        tv1_2.setText(all);
                        mOrder = ServerApi.CP_REPAY;
                        mSort = "a";
                    }
                    else
                    {
                        all = all + "∨";
                        tv1_2.setText(all);
                        mOrder = ServerApi.CP_REPAY;
                        mSort = "d";
                    }
                    returnInvestmentClickTime++;
//                    initChipsList(true,1,mOrder,mSort,mCp_hoot_date,mCp_release_time,mSearch);
                String allb = getResources().getString(R.string.all);
                tv1_1.setText(allb);
                String support_number = getResources().getString(R.string.support_number);
                tv1_3.setText(support_number);
            }
        });

        tv1_3 = (TextView) findViewById(R.id.tv_3);
        tv1_3.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                String all = getResources().getString(R.string.support_number);
                if (supportNumberClickTime%2==0)
                {
                    all = all + "∧";
                    tv1_3.setText(all);
                    mOrder = ServerApi.CP_CURRENT_CNT;
                    mSort = "a";
                }
                else
                {
                    all = all + "∨";
                    tv1_3.setText(all);
                    mOrder = ServerApi.CP_CURRENT_CNT;
                    mSort = "d";
                }
                supportNumberClickTime++;
//                initChipsList(true,1,mOrder,mSort,mCp_hoot_date,mCp_release_time,mSearch);
                String allb = getResources().getString(R.string.all);
                tv1_1.setText(allb);
                String support_number = getResources().getString(R.string.return_investment);
                tv1_2.setText(support_number);
            }
        });
    }

    //点击次数
    int allClickTime = 0;
    int returnInvestmentClickTime = 0;
    int supportNumberClickTime = 0;

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case android.R.id.home:
                finish();
                break;
            case R.id.action_screen_sx_item:
//                mDrawerLayout.openDrawer(right_drawer);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_notbtn, menu);
//        MenuItem menuItem = menu.findItem(R.id.action_search);//在菜单中找到对应控件的item
//        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
//        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
//        {
//
//            public boolean onQueryTextSubmit(String query)
//            {
//                mSearch = query;
//                initChipsList(1,mOrder,mSort,mCp_hoot_date,mCp_release_time,mSearch);
//                return true;
//            }
//
//            public boolean onQueryTextChange(String newText)
//            {
//                return true;
//            }
//        });



//        Log.d("Tag", "menu create");
//        MenuItemCompat.setOnActionExpandListener(menuItem, new MenuItemCompat.OnActionExpandListener() {//设置打开关闭动作监听
//            @Override
//            public boolean onMenuItemActionExpand(MenuItem item)
//            {
//                Toast.makeText(ProjectActivity.this, "onExpand", Toast.LENGTH_LONG).show();
//                return true;
//            }
//
//            @Override
//            public boolean onMenuItemActionCollapse(MenuItem item)
//            {
//                Toast.makeText(ProjectActivity.this, "Collapse", Toast.LENGTH_LONG).show();
//                return true;
//            }
//        });
        return super.onCreateOptionsMenu(menu);
    }

    //===========================更新队列==============
    FilmProjectFilter filmProjectFilter;
    final Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            if(msg.what == 1)
            {
//                flowLayoutRadioGroupList = new ArrayList<FlowLayoutRadioGroup>();
//                initRightViewData(getString(R.string.shooting_date),filmProjectFilter.cpHootDateList);
//                initRightViewData(getString(R.string.release_time),filmProjectFilter.cpReleaseTimeList);
            }

        }
    };


    //刷新职数据
    public void requestData()
    {
        initChipsList(true,1,mOrder,mSort,mCp_hoot_date,mCp_release_time,mSearch);

    }
    //添加职数据
    public void morePeopleData()
    {
        initChipsList(false,mPage,mOrder,mSort,mCp_hoot_date,mCp_release_time,mSearch);
    }

}
